package edu.nf.api.controller.user;

import com.google.gson.Gson;
import edu.nf.api.controller.BaseController;
import edu.nf.waimai.dao.user.UserDAO;
import edu.nf.waimai.dao.user.impl.UserDaoImpl;
import edu.nf.waimai.model.user.Address;
import edu.nf.waimai.model.user.User;
import org.nf.web.annotation.Model;
import org.nf.web.annotation.RequestMapping;
import org.nf.web.annotation.RequestParam;
import org.nf.web.servlet.View;
import org.nf.web.servlet.view.JsonView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @Date 2023/6/28
 * @Author zgm
 * 查看个人信息
 */
public class PersonalController extends BaseController {
    @RequestMapping("/user")
    public View queryUser(HttpServletRequest request, HttpServletResponse response){
        // 第一：从请求作用域中，获取登录的帐号
        String username = (String)request.getAttribute("username");

        UserDAO userDao = new UserDaoImpl();
        User user = userDao.loginUser(username);
        user.setUpwd(null);

        // 第二：响应结果
        return new JsonView(success(user));
    }

    // 查询用户地址
    @RequestMapping("/user/Address")
    public View queryListUserAddress(@RequestParam("uid") Integer uid){
        UserDAO dao = new UserDaoImpl();
        List<Address> list = dao.queryListUserAddress(uid);
        return new JsonView(success(list));
    }
    // 查询用户地址
    @RequestMapping("/queryAddressById")
    public View queryUserAddressById(@RequestParam("addressId") Integer addressId){
        UserDAO dao = new UserDaoImpl();
        Address address = dao.queryUserAddressById(addressId);
        return new JsonView(success(address));
    }

    // 增加用户地址
    @RequestMapping("/insertAddress")
    public View insertAddress(@RequestParam("address") String address){
        System.out.println(address);
        Address address1 = new Gson().fromJson(address, Address.class);
        UserDAO dao = new UserDaoImpl();
        int row = dao.insertAddress(address1);
        return row >= 1 ? new JsonView(success()) :  new JsonView(error("增加失败"));
    }
    // 编辑用户地址
    @RequestMapping("/updateAddressById")
    public View updateAddress(@RequestParam("address") String address){
        Address address1 = new Gson().fromJson(address, Address.class);
        UserDAO dao = new UserDaoImpl();
        int row = dao.updateAddress(address1);
        return row >= 1 ? new JsonView(success()) :  new JsonView(error("编辑失败"));
    }
    // 查询用户地址
    @RequestMapping("/getAddressById")
    public View getAddressById(@Model Address address){
        System.out.println(address);
        UserDAO dao = new UserDaoImpl();
        Address address1 = dao.getUserAddress(address);
        return new JsonView(success(address1));
    }
}
